package com.imooc.distributedemo.resume.leetcode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * leetcode347 前N个高频元素
 */
public class Solution347 {
    public static void main(String[] args) {
        int[] nums = {1,1,1,2,2,3};
        int[] arr = topKFrequent(nums,2);
        System.out.println(arr);
    }

    public static int[] topKFrequent(int[] nums, int k) {
        if (null == nums || nums.length < 1) {
            return null;
        }
        Map<Integer, Integer> counter = new HashMap<>();
        for (int num : nums) {
            counter.put(num, counter.getOrDefault(num, 0) + 1);
        }
        // List<Entry<Integer, Integer>> entries = (ArrayList) counter.entrySet();
        List<Map.Entry<Integer, Integer>> entries = new ArrayList<>(counter.entrySet());
        entries.sort((entry1, entry2) -> entry2.getValue() - entry1.getValue());
        // 获取出现频率最高的前K个数
        List<Integer> topK = new ArrayList<>();
        for (int i = 0; i < k; i++) {
            topK.add(entries.get(i).getKey());
        }
        int[] result = topK.stream().mapToInt(i -> i).toArray();
        return result;
    }
}
